package com.talkology.pilot.student.service.impl;

import com.talkology.pilot.database.dao.CouponMapper;
import com.talkology.pilot.database.model.Coupon;
import com.talkology.pilot.student.service.ICouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private CouponMapper mapper;

    @Override
    public List<Coupon> getAllByFilter(Integer useFlag, Integer classNum) {
        return mapper.getAllByFilter(useFlag, classNum);
    }

    @Override
    public Coupon getInfo(Integer index) {
        return mapper.selectByPrimaryKey(index);
    }

    @Override
    @Transactional
    public void add(Coupon record) {
        if (record.getUserName() != null || record.getUseFlag() != 0 || record.getClassNum() <= 0) {
            throw new RuntimeException("Wrong input");
        }
        mapper.insert(record);
    }

    @Override
    @Transactional
    public void edit(Coupon record) {
        if (record.getClassNum() <= 0 || record.getIndex() == null) {
            throw new RuntimeException("Wrong input.");
        }
        if (record.getUserName() != null || record.getUseFlag() != 0) {
            throw new RuntimeException("Was used, cannot be modified");
        }
        mapper.updateByPrimaryKey(record);
    }

    @Override
    @Transactional
    public void delete(Integer index) {
       Coupon coupon = mapper.selectByPrimaryKey(index);
       if (coupon.getUseFlag() == 1) {
           throw new RuntimeException("Was used, cannot be delete.");
       }
        mapper.deleteByPrimaryKey(index);
    }
}
